var dataListObj = {} ;
var $suggestion = {} ;
$(function() {
	$('input[ref="suggestion"]').bind("focus", function() {
	//$('#userCompany').bind("focus", function() {
		var $this = $(this) ;
		$suggestion = $(this) ;
		dataListObj = $this.wendaDropDrownList({
			"width" : 320,
			"top" : $this.parent().offset().top + $this.parent().height(),
			"left" : $this.parent().offset().left,
			"searchFun" : "suggestTargetObj"
		});
		scrollEvent = "dataListObj.setConfig({\"top\":$suggestion.offset().top + $suggestion.height(),\"left\":$suggestion.offset().left})";
	});
});

function addTargetObj(obj, stype) {
	// console.log('--------' + stype + '***over') ;
	var name = "" ;
	var $this = $(obj) ;
	var $text = $this.find("span");
	if (stype == 'company') {
		$("#userCompanyId").val($text.data('companyid'));
		$("#userCompany").val($text.text());
	} else {
		$suggestion.val($text.text());
	}
}

var _timeout;
function suggestTargetObj (target, stype) {
	//使用定时器，当用户停止输入后调用，防止用户输入时不断的发送http请求
	if(_timeout){
		clearTimeout(_timeout);
	}
	_timeout = setTimeout(function(){
		// console.log('------------ccccc--' + stype);
		if(target != null || target.trim() != ''){
			var _target={'keyword':target};
			var url = '' ;
			if (stype == 'position') {
				url = basePath + 'search/suggest!position.action' ;
			} else if (stype == 'company') {
				url = basePath + 'search/suggest!company.action' ;
			} else if (stype == 'department') {
				url = basePath + 'search/suggest!department.action' ;
			}else {
				return ;
			}
			jQuery.ajax({
				type: 'post',
				url: url,
				data: _target,
				success:  function(data) {
					builtHtml(data, stype);
				},
				error:function(data){
					builtHtml(data, stype);
				},
				dataType: 'json'
			});
		}
	},500);
	
	function builtHtml(data, stype){
		var i = 0;
		var html = '';
		if (data.length == 0) {
			if (stype == 'company') {
				$("#userCompanyId").val("");
			}
		}
		for(var n in data){
			var index = i++;
			var name = data[index].value;
			var companyId = data[index].key;
			if (stype == 'company') {
				html += '<div class="ac-row" style="-moz-user-select: none;" onclick="addTargetObj(this,\'' + stype + '\')">'
					+'<span data-companyid="' + companyId + '" title="'+name+'" class="" style="-moz-user-select: none;">' 
					+ (name == null ? "" : name) + '</span></div>';
			} else {
				html += ['<div class="ac-row" style="-moz-user-select: none;" onclick="addTargetObj(this,\'' + stype + '\')">',
				         '	<span title="'+name+'" class="" style="-moz-user-select: none;">' + (name == null ? "" : name) + '</span>',
				         '</div>'
					    ].join('');
			}
		}
		dataListObj.setHtml({"html":html});
	}
} ;